package com.example.baseapp.common.exception;

import com.example.baseapp.common.Result;
import com.example.baseapp.common.enums.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;


/**
 * RestExceptionHandler class
 *
 * @author zhangl
 * @date 2022/3/23 16:07
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler(DataIntegrityViolationException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> sqlException(DataIntegrityViolationException e){
        log.error("数据库异常：[{}]",e);
        return Result.fail(ResponseCode.SEQ_EXCEPTION.getCode(),ResponseCode.SEQ_EXCEPTION.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> methodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("参数校验异常：{}",e);
        return Result.fail(ResponseCode.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getCode(),ResponseCode.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getMessage()+e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";")));
    }
    @ExceptionHandler( ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> constraintViolationException(ConstraintViolationException e){
        log.warn("自定义校验：{}",e);
        String msg = e.getMessage().substring(e.getMessage().indexOf(":"));
        return Result.success(ResponseCode.DATA_VALIDATION_FAILED.getCode(),msg);
    }
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> businessException(BusinessException e){
        return Result.success(e.getCode(),e.getMessage());
    }

    /**
     * 默认处理全局异常
     * @param e Exception
     * @return Result<String>
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<String> exception(Exception e){
        log.warn("{}",e);
        return Result.fail(ResponseCode.RC500.getCode(),ResponseCode.RC500.getMessage());
    }


}
